<?php

error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '128M');

$g_start = microtime(true);
require_once "config.php";
require_once dirname(__FILE__). '/util/connection.class.php';
$dbconn = Connection::getInstance();

$toSubUsersId = getToSentUsers($dbconn);
if(count($toSubUsersId)>0){
	$usersInfo = getUsersInfo($toSubUsersId, $dbconn);
	inPaysSent($usersInfo, $dbconn);
}

echo "\n". (microtime(true)-$g_start) . " seconds\n";



function getToSentUsers(Connection $db)
{
	$sql = "SELECT uid FROM inpays_optin WHERE status='tosent' limit 1";
	try{
		$result = $db->query($sql);
		if(!empty($result)){
			foreach($result as $k=>$v){
				$result[$k] = $v['uid'];
			}	
		}
		return $result;
	}catch(Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function getUsersInfo($usersId, Connection $db)
{
	$sql = " SELECT u.*, s.name AS site_name FROM users u LEFT JOIN sites s ON u.site_id = s.id WHERE u.id IN ( " . implode(', ', $usersId) . " ) ";
	try{
		$result = $db->query($sql);
		return $result;
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

function inPaysSent($usersInfo, Connection $db)
{
	foreach($usersInfo as $user){
		$advertiserId = 546;
		$urlArgs = array('aff'=>$advertiserId, 'saff'=>$user['site_name'], 'fn'=>$user['firstname'], 'ln'=>$user['lastname'], 
						 'em'=>$user['email'], 'ip'=>long2ip($user['ip']), 'zip'=>$user['zipcode'], 'dj'=>date('Y-m-d'), 'sn'=>$user['site_name'], 'dob'=>$user['birthday']
		);

		$ch = curl_init();
		$url = "http://www.inboxpays.com/coreg?";
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($urlArgs, '', '&'));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		$content = curl_exec($ch);
		curl_close($ch);
		print_r($content);
		
		setStatusSub( $user['id'] ,$content, $db);
	}
}

function setStatusSub($userId, $response, Connection $db)
{
	$status = 'sent_failed';
	if(strpos(strtolower($response), 'successful') !== false){
		$status = 'sent';
	}
	
	$sql = "UPDATE inpays_optin SET status=?, send_date=?, response=? WHERE uid=? ";
	echo '' . $userId. "\n";
	try{
		$result = $db->execute($sql, array( $status , date('Y-m-d'), $response, $userId));
		echo ''. $result . "\n";
	}catch (Exception $e){
		QLog::log(__CLASS__.' '.__METHOD__.' --- '.$e->getMessage(), QLog::ERR);
		throw new Model_Exception($e->getMessage(), $e->getCode());
	}
}

	
	
	
	
	
	
	